import _ from "lodash";
import { createStore } from "vuex";
import modules from "./modules";
import Api from "../components/tools/api";
import Message from "../components/message/index";
import { DispatchResult } from "../tools";

import { v4 as uuidv4 } from "uuid";

const tagKey = "user_tag";
let tag = localStorage.getItem(tagKey);
if (!tag) {
  tag = uuidv4();
  localStorage.setItem(tagKey, tag);
}

const state = {
  uid: undefined,
  tag,
  logs: [],
  options: {},
};

const getters = {};

const mutations = {};

const actions = {
  async userLogin({ state }: any) {
    try {
      console.log("userLogin", state.tag);
      const result = await Api.send("/game/userLogin", {
        tag: state.tag,
      });
      DispatchResult(result, {
        onSuccess: (data: any) => {
          state.uid = data.id;
        },
        onError: (_data: any, message: string) => {
          Message({ message, type: "error" });
        },
      });
    } catch (error) {
      console.log(error);
    }
  },

  async updateOptions({ state }: any) {
    try {
      const result = await Api.send("/common/options");
      DispatchResult(result, {
        onSuccess: (data: any) => {
          let tr = data["skillTargetAllowed"];
          if (Array.isArray(tr)) {
            tr = tr.map((item) => {
              if (item.type === "group") {
                return item.list;
              }
              return item;
            });
            tr = _.flatMap(tr);
          }
          data["skillTargetAllowed"] = tr;
          state.options = data;
        },
        onError: (_data: any, message: string) => {
          Message({ message, type: "error" });
        },
      });
    } catch (error) {
      console.log(error);
    }
  },
};

export default createStore({
  state,
  getters,
  mutations,
  actions,
  modules,
});
